<template>
    <div class="white-box-form">
        <el-form
            ref="ruleRef"
            :model="state.ruleForm"
            :rules="state.rules"
            label-width="120px"
            class="mt-20"
        >
            <el-form-item label="线路" prop="lineSid">
                <SelectLoadMore
                    v-model:selectValue="state.ruleForm.lineSid"
                    v-model:options="state.lineOptions"
                    v-model:needFilterOptions="state.needFilterLineOptions"
                    value="sid"
                    label="lineName"
                    popperClass="line"
                    placeholder="请选择线路"
                    :apiFun="getLineOptions"
                />
            </el-form-item>
            <el-form-item
                v-if="state.ruleForm.lineSid"
                label="运输方式"
                prop="toolCode"
            >
                <el-select
                    v-model="state.ruleForm.toolCode"
                    placeholder="请选择运输方式"
                    clearable
                >
                    <el-option
                        v-for="item in state.toolOptions"
                        :key="item.vehicleCode"
                        :label="item.vehicleName"
                        :value="item.vehicleCode"
                    />
                </el-select>
            </el-form-item>
            <!-- 非陆运才显示 -->
            <el-form-item
                v-if="
                    state.ruleForm.toolCode && state.ruleForm.toolCode !== 'BUS'
                "
                label="车次号"
                prop="code"
            >
                <el-input
                    placeholder="请输入车次号"
                    v-model="state.ruleForm.code"
                    clearable
                ></el-input>
            </el-form-item>
            <template
                v-if="
                    state.ruleForm.toolCode && state.ruleForm.toolCode === 'BUS'
                "
            >
                <el-form-item
                    v-if="state.ruleForm.lineSid"
                    label="车辆"
                    prop="carSid"
                >
                    <SelectLoadMore
                        v-model:selectValue="state.ruleForm.carSid"
                        v-model:options="state.carOptions"
                        v-model:needFilterOptions="state.needFilterCarOptions"
                        value="sid"
                        label="carNumber"
                        popperClass="car"
                        placeholder="请选择车辆"
                        :apiFun="getCarOptions"
                    />
                </el-form-item>
                <el-form-item
                    v-if="state.ruleForm.lineSid && state.ruleForm.carSid"
                    label="运单"
                    prop="waybillSid"
                >
                    <div>
                        <el-table
                            v-if="state.confirmSelectedWaybills.length"
                            class="mb-10 w-1100 line-height-23"
                            :data="state.confirmSelectedWaybills"
                            row-key="sid"
                            :header-cell-style="{
                                background: '#F5F7FA',
                                textAlign: 'center',
                            }"
                            :cell-style="{
                                textAlign: 'center',
                            }"
                            border
                            max-height="250"
                            element-loading-background="rgba(255, 255, 255, 0.6)"
                            @sort-change="sortChange"
                        >
                            <el-table-column
                                prop="wayBillCode"
                                label="运单流水号"
                                min-width="200"
                                fixed="left"
                            ></el-table-column>
                            <el-table-column
                                prop="orderCode"
                                label="订单流水号"
                                min-width="200"
                            ></el-table-column>
                            <el-table-column
                                prop="ownerName"
                                label="下单用户"
                                min-width="140"
                                :show-overflow-tooltip="{
                                    'popper-class': 'max-w-800',
                                }"
                            ></el-table-column>
                            <el-table-column
                                prop="preserve"
                                label="保藏方式"
                                min-width="140"
                            ></el-table-column>
                            <el-table-column
                                prop="vehicle"
                                label="运输方式"
                                min-width="140"
                            ></el-table-column>
                            <el-table-column
                                prop="realAmount"
                                label="实际金额"
                                min-width="140"
                            >
                                <template #default="{ row }">
                                    {{ fenToYuan(row.realAmount) }}元
                                </template>
                            </el-table-column>
                            <el-table-column
                                label="操作"
                                min-width="80"
                                fixed="right"
                            >
                                <template #default="{ row, $index }">
                                    <MoreBtn
                                        :buttons="[
                                            {
                                                props: {
                                                    onClick: () =>
                                                        delWaybill($index),
                                                },
                                                text: '删除',
                                            },
                                        ]"
                                    />
                                </template>
                            </el-table-column>
                        </el-table>
                        <el-button
                            v-if="state.ruleForm.lineSid"
                            plain
                            type="primary"
                            size="small"
                            @click="onClickChooseWaybill"
                            >选择运单</el-button
                        >
                    </div>
                </el-form-item>
            </template>

            <el-form-item label="备注" prop="note">
                <el-input
                    v-model.trim="state.ruleForm.note"
                    type="textarea"
                    maxlength="100"
                    :autosize="{ minRows: 2 }"
                    clearable
                    show-word-limit
                    placeholder="请输入备注"
                />
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-radio-group v-model="state.ruleForm.status">
                    <el-radio
                        v-for="item in state.statusList"
                        :key="item.memberKey"
                        :value="item.memberKey"
                        >{{ item.memberName }}</el-radio
                    >
                </el-radio-group>
            </el-form-item>
        </el-form>
        <div class="foot-btn">
            <el-button
                type="primary"
                :loading="form_loading"
                @click="submitForm(ruleRef)"
            >
                保存
            </el-button>
            <!-- <el-button
                v-hasPermi="['enttp:waybill:assignDriverDeparture']"
                type="primary"
                @click="onClickAssign"
                >分配司机发车</el-button
            > -->
        </div>
        <go-back />
    </div>

    <el-dialog
        v-model="state.showWaybillTable"
        title="选择运单"
        top="5vh"
        width="1200px"
    >
        <div class="task-one">
            <div class="task-one__item">
                <span class="task-one__label">订单/运单流水号：</span>
                <el-input
                    placeholder="请输入订单或运单流水号"
                    v-model="state.code"
                    @keyup.enter.native="handleSearch"
                    clearable
                >
                </el-input>
            </div>
            <div class="task-one__btn clearfix">
                <el-button
                    type="primary"
                    :loading="loading"
                    icon="Search"
                    @click="handleSearch"
                    >搜索</el-button
                >
            </div>
        </div>

        <el-table
            class="table-mb"
            v-loading="loading"
            :data="arr_data"
            row-key="sid"
            :header-cell-style="{
                background: '#F5F7FA',
                textAlign: 'center',
            }"
            :cell-style="
                ({ column }) => {
                    return {
                        textAlign:
                            column.className === 'operation-nav'
                                ? 'left'
                                : 'center',
                        paddingLeft:
                            column.className === 'operation-nav' ? '25px' : '0',
                    };
                }
            "
            border
            max-height="450"
            element-loading-background="rgba(255, 255, 255, 0.6)"
            @sort-change="sortChange"
        >
            <el-table-column
                prop="wayBillCode"
                label="运单流水号"
                min-width="200"
                fixed="left"
            ></el-table-column>
            <el-table-column
                prop="orderCode"
                label="订单流水号"
                min-width="200"
                fixed="left"
            ></el-table-column>
            <el-table-column
                prop="ownerName"
                label="下单用户"
                min-width="140"
                :show-overflow-tooltip="{
                    'popper-class': 'max-w-800',
                }"
            ></el-table-column>
            <el-table-column
                prop="preserve"
                label="保藏方式"
                min-width="140"
            ></el-table-column>
            <el-table-column
                prop="vehicle"
                label="运输方式"
                min-width="140"
            ></el-table-column>
            <el-table-column
                prop="realAmount"
                label="实际金额"
                min-width="150"
                sortable="custom"
                fixed="right"
            >
                <template #default="{ row }">
                    {{ fenToYuan(row.realAmount) }}元
                </template>
            </el-table-column>
            <el-table-column min-width="100" fixed="right">
                <template #header>
                    <el-checkbox
                        v-if="arr_data.length"
                        v-model="isSelectedCurPageAll"
                        :indeterminate="isIndeterminate"
                        @change="selectAll"
                    />
                </template>
                <template #default="{ row }">
                    <el-checkbox
                        v-model="row.checked"
                        @change="onCheckboxChange(row, $event)"
                    />
                </template>
            </el-table-column>
        </el-table>
        <div class="flex justify-between">
            <el-pagination
                background
                v-model:current-page="page"
                v-model:page-size="pageSize"
                :page-sizes="pageSizeNum"
                :total="totalNums"
                layout="slot, sizes, prev, pager, next, jumper"
            >
                <span class="color-#606266"
                    >共&nbsp;{{
                        totalNums >= 100 * pageSize
                            ? `${100 * pageSize}+`
                            : totalNums
                    }}&nbsp;条</span
                >
            </el-pagination>
            <el-button type="primary" @click="confirmSelect">确定</el-button>
        </div>
    </el-dialog>

    <el-dialog
        v-model="state.showAssign"
        title="分配司机发车"
        width="350"
        destroy-on-close
    >
        <DriverDeparture @success="successDriverDeparture" />
    </el-dialog>
</template>

<script setup>
import { inject, ref, onMounted, reactive, watch, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import GoBack from "@components/GoBack.vue";
import {
    getWaybillLines,
    getUndeliveredWaybillsByLine,
    getWaybillCars,
    getCarsByLine,
    entrucking,
} from "@/apis/order/waybill";
import { getTripDetail, editTrip } from "@/apis/order/trip";
import DriverDeparture from "./DriverDeparture.vue";
import SelectLoadMore from "@/components/selectLoadMore.vue";
import OneLoad from "@mixins/one-load";
import MoreBtn from "@/components/MoreBtn.vue";
import { fenToYuan } from "@/assets/common/utils.js";
import { useDictStore } from "@stores/dict.js";
import { getLineConfigs } from "../../../apis/enterprise/line";

const dictStore = useDictStore();
dictStore.getDictMembers("data_status").then((res) => (state.statusList = res));

const router = useRouter();
const route = useRoute();
const $message = inject("$message");

const sid = route.query.sid;
const isEdit = ref(false);
const form_loading = ref(false);
const ruleRef = ref(null);
const state = reactive({
    statusList: [],
    ruleForm: {
        lineSid: null,
        waybillSid: [],
        carSid: null,
        note: null,
        status: 0,
        toolCode: null,
        code: null,
    },
    rules: {
        lineSid: [{ required: true, message: "请选择线路", trigger: "blur" }],
        toolCode: [
            { required: true, message: "请选择运输方式", trigger: "blur" },
        ],
        code: [{ required: true, message: "请输入车次号", trigger: "blur" }],
        waybillSid: [
            { required: true, message: "请选择运单", trigger: "blur" },
        ],
        carSid: [{ required: true, message: "请选择车辆", trigger: "blur" }],
    },
    lineOptions: [],
    needFilterLineOptions: [],
    carOptions: [],
    needFilterCarOptions: [],
    showWaybillTable: false,
    ascended: false,
    sortFieldName: null,
    carrier: null,
    code: null,
    wayBillState: 1,
    selectedWaybills: [],
    confirmSelectedWaybills: [], // 确认选择的运单
    showAssign: false, // 发车
    toolOptions: [], // 运输方式选项
});

// 切换线路和车辆清空已选择运单
watch([() => state.ruleForm.lineSid, () => state.ruleForm.carSid], () => {
    state.confirmSelectedWaybills = [];
});

// 是否选中运单列表中当前页所有运单
const isSelectedCurPageAll = computed(() => {
    return (
        state.selectedWaybills.filter((item) => item.page === page.value)
            .length === arr_data.value.length
    );
});

// 是否部分选中运单列表中当前页运单
const isIndeterminate = computed(() => {
    return (
        state.selectedWaybills.some((item) => item.page === page.value) &&
        !isSelectedCurPageAll.value
    );
});

onMounted(() => {
    if (/Edit$/.test(route.name)) {
        isEdit.value = true;
    }
    if (sid) {
        getDetail();
    }
});

const getDetail = async () => {
    const res = await getTripDetail({ sid });
    if (res.data.code == 200) {
        const { sid, carResult, lineResult, waybillResult, note, status } =
            res.data.data;

        state.ruleForm.sid = sid;
        state.ruleForm.lineSid = lineResult.sid;
        // watch 监听了 state.selectedWaybills，会更新 state.ruleForm.waybillSid
        state.selectedWaybills = waybillResult;
        state.ruleForm.carSid = carResult.sid;
        state.ruleForm.note = note;
        state.ruleForm.status = status;

        // 添加选项到远程加载下拉框
        state.lineOptions.push(lineResult);
        state.needFilterLineOptions.push(lineResult);

        state.carOptions.push(carResult);
        state.needFilterCarOptions.push(carResult);
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

const getLineOptions = async (params) => {
    const res = await getWaybillLines({
        ...params,
        lineName: params.keyword,
    });
    if (res.data.code == 200) {
        return res;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

const getCarOptions = async (params) => {
    const res = await getCarsByLine({
        ...params,
        lineSid: state.ruleForm.lineSid,
    });
    if (res.data.code == 200) {
        return res;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

const onClickChooseWaybill = () => {
    state.showWaybillTable = true;
    state.selectedWaybills = JSON.parse(
        JSON.stringify(state.confirmSelectedWaybills)
    );
    pubParams(getList);
};

const onCheckboxChange = (row, checked) => {
    const index = state.selectedWaybills.findIndex(
        (item) => item.sid === row.sid
    );
    const isSelected = index > -1;
    if (checked) {
        !isSelected &&
            state.selectedWaybills.push({ ...row, page: page.value });
    } else {
        isSelected && state.selectedWaybills.splice(index, 1);
    }
};

const selectAll = (checked) => {
    arr_data.value.forEach((item) => {
        item.checked = checked;
        onCheckboxChange(item, checked);
    });
};

const confirmSelect = () => {
    state.confirmSelectedWaybills = JSON.parse(
        JSON.stringify(state.selectedWaybills)
    );
    state.showWaybillTable = false;
};

// 删除已选择的运单
const delWaybill = (index) => {
    state.confirmSelectedWaybills.splice(index, 1);
};

/**
 * minxin列表加载
 */
const {
    loading,
    arr_data,
    pubRefreshParams,
    pubParams,
    page,
    pageSize,
    getdata,
    pageSizeNum,
    totalNums,
    openPaging,
} = OneLoad();

openPaging(getList);

function getList() {
    getdata(
        getUndeliveredWaybillsByLine({
            lineSid: state.ruleForm.lineSid,
            carSid: state.ruleForm.carSid,
            current: page.value,
            size: pageSize.value,
            ascended: state.ascended,
            sortFieldName: state.sortFieldName,
            carrier: state.carrier,
            code: state.code,
            wayBillState: state.wayBillState,
        })
    );
}

watch(
    () => arr_data.value,
    (val) => {
        val.forEach((item) => {
            item.checked = state.ruleForm.waybillSid.includes(item.sid);
        });
    }
);

watch(
    [() => state.selectedWaybills, () => page],
    ([val]) => {
        state.ruleForm.waybillSid = val.map((item) => item.sid);
    },
    {
        deep: true,
    }
);

watch(
    () => state.ruleForm.lineSid,
    (newVal) => {
        if (newVal) {
            getLineConfigs({ sid: newVal }).then((res) => {
                state.toolOptions = res.data.data;
				// state.toolOptions = res.data.data.vehicleList;
            });
        } else {
            state.toolOptions = [];
        }
    }
);

// 搜索
const handleSearch = () => {
    pubRefreshParams(getList);
};

// 排序
const sortChange = (e) => {
    const { property, order } = e.column;
    state.ascended = order === "ascending";
    state.sortFieldName = order ? property : null;
    pubRefreshParams(getList);
};

// 提交表单
const submitForm = (formEl) => {
    if (!formEl) return;
    formEl.validate(async (valid, fields) => {
        if (valid) {
            form_loading.value = true;
            let res;
            if (isEdit.value) {
                res = await editTrip(state.ruleForm);
            } else {
                res = await entrucking(state.ruleForm);
            }
            form_loading.value = false;
            if (res.data.code == 200) {
                $message({
                    message: isEdit.value ? "修改成功" : "保存成功",
                    type: "success",
                });
                router.back();
            } else {
                $message({ message: res.data.msg, type: "error" });
            }
        }
    });
};

// 显示分配司机发车弹窗
const onClickAssign = () => {
    state.showAssign = true;
};

const successDriverDeparture = () => {
    state.showAssign = false;
};


</script>

<style lang="less" scoped>
:deep(.el-table__inner-wrapper:before) {
    height: 0;
}
</style>
